<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/10/12
 * Time: 20:05
 */

namespace app\api\controller;
//use app\api\model\UserActivity;
//use app\cx\model\Order;
//use app\cx\model\Wxcallback;
use app\api\model\Balance;
use app\api\model\Pull;
use think\Db;
use app\api\model\Order;
use app\api\model\User;
use app\api\model\UserSubscribe;
use app\api\model\Magazine;
use app\api\model\Course;
use app\api\model\TalkShow;
/**
 * Class Pay
 * @package app\api\controller
 * 微信支付
 */
class Pay extends Basic
{

    //初始化父类
    public function _initialize()
    {
        parent::_initialize();
    }

    //支付成功
    public function pay_success(){
        //查询是否实名认证
        if ($this->is_certification() ==false){
            json_fail([
                'status' => -1,
                'msg' => '请先实名认证!'
            ]);
        }
        if (!$this->user_id){
            json_fail([
                'status' => -1,
                'msg' => '用户ID不存在！'
            ]);
        }
        $order_id= Input('order_id');
        if (!$order_id){
            json_fail([
                'status' => -1,
                'msg' => '订单ID不存在！'
            ]);
        }
        $order = new Order();
        $order_data = $order->where('user_id',$this->user_id)->where('id',$order_id)->field('sn,pay_time,pay_price')->find()->toArray();
        if (!$order_data){
            json_fail([
                'status' => -1,
                'msg' => '未查到订单信息！'
            ]);
        }else{
            $order_data['pay_time'] = date('Y-m-d H:i:s',$order_data['pay_time']);
            $order_data['pay_price'] =  $order_data['pay_price'] /100;
            json_success($order_data);
        }
    }

    /**
     * 支付回调
     * @author jihaichuan
     */
    public function order_notify_url(){
        $xmlStr = file_get_contents('php://input');
        vendor('Wxpay.WxPayResults');
        // 将XML转换成数组
        $WxPayResults = new \WxPayResults();
        $data = $WxPayResults::Init($xmlStr);
        //判断是否支付成功
        if (($data['return_code'] == "SUCCESS") && ($data['result_code']=='SUCCESS')) {
            //修改数据
            $result=$this->update_order($data);
        }else{
            $result=false;
        }
        if ($result){
            $str= '<xml>
          <return_code><![CDATA[SUCCESS]]></return_code>
          <return_msg><![CDATA[OK]]></return_msg>
                    </xml>';
        }else{
            $str='<xml>
          <return_code><![CDATA[FAIL]]></return_code>
          <return_msg><![CDATA[签名失败]]></return_msg>
                    </xml>';
        }
        echo $str;
        return $result;
    }


    /**
     * 获取当前金额
     * @return mixed
     * @author jihaichuan
     */
    public function get_current_price($user_id)
    {

//        $info = \app\api\model\User::where('id', UID)->find();
//        if (!$info) {
//            return 0;
//        }

        // 获取用户已提现金额
        $user_balance = new Balance();
        // 获取总金额
        $total_price = $user_balance->where(array(
            'type' => 1,      //1收入总金额
            'user_id' => $user_id
        ))->sum('price');

        if (empty($total_price))
        {
            $total_price=0;
        }

        //提现金额
        $receive_price = $user_balance->where(array(
            'type' => 2,            //2 提现总金额
            'user_id' => $user_id
        ))->where('is_arrival','neq', 3)->sum('price');
        if (empty($receive_price)){
            $receive_price=0;
        }
        // 判断提现金额是否超过获得金额
        $price = $total_price - $receive_price;
        if ($price < 0) {
            return 0;
        }
        // 返回用户当前 金额
        return $price;
    }





    /**
     * 支付成功后修改订单表
     *    附加【attach】参数选择传递订单类型type,
     *      【attach】 参数
     *      【1】年份杂志订单
     *      【2】单期杂志订单
     *      【3】小课订单
     *      【4】TalkShow订单
     *      【5】开通VIP会员订单
     */
    public function update_order($data)
    {
        if (empty($data)){
            return false;
        }
        //查询订单详情
        $order=Order::field('id,user_id,sn,type,buy_type,pid,price,pay_price,is_pay,create_time,pay_time,status')
            ->where('sn',$data['out_trade_no'])->find();
        if ($order['is_pay']!=1) {

            //查询用户详情
//            $field = ['id', 'source_id', 'source_type', 'is_vip', 'openid', 'subscribe_count', 'order_count', 'drainage_count', 'vip_start_time', 'vip_end_time', 'total_consume_price', 'total_profit_price', 'total_receive_price', 'year_magazine_start_time', 'year_magazine_end_time', 'is_year_magazine'];
            //支付金额
            $pay_price = $data['total_fee'];

            $user = User::where('id', $order['user_id'])->find();

            //更新用户的订单数量 +1
            User::where('id', $order['user_id'])->setInc('order_count');

            //更新用户的消费总金额
            User::where('id', $order['user_id'])->setInc('total_consume_price', $pay_price);
            //如果有邀请者 , 更新邀请者的收益
            if ($user['source_type'] == 2) {

                //分享者的信息
//                $user_invite = User::field($field)->where('id', $user['source_id'])->find();
                $user_invite = User::where('id', $user['source_id'])->find();
                //设置给邀请者的 收益金额  为用户支付金额的一定比例

                //  收益规则  10%
                $invite_price=$pay_price*30/100;

                if ($user_invite) {
                    //增加邀请者总收益
                    User::where('id', $user_invite['id'])->setInc('total_profit_price', $invite_price);

                    $old_price = $this->get_current_price($user_invite['id']);  //邀请者的当前收益

                    //设置收支记录表  为邀请者加入一条新的收益记录
                    $create_balance = [
                        'type' => 1,                                               //收入
                        'user_id' => $user['source_id'],                           //邀请者ID
                        'price' => $invite_price,                                  //收支金额
                        'current_price' => $old_price + $invite_price,               //当前金额
                        'is_arrival' => 0,                                         //是否钱已到账：【1:已到账】【2:提现未到账】【3:待提现】
                        'time' => time(),                                          //创建时间
                    ];
                    //新增用户收支记录
                    $balance = new Balance();
                    $balance->data($create_balance);
                    $balance->save();

                    //修改用户好友表该用户收益总金额
                    Pull::where('share_user_id', $user_invite['id'])->where('user_id', $order['user_id'])->setInc('total_price', $invite_price);

                }
            }

            //判断支付类型
            if ($data['attach'] == 1) {
                if ($user['is_year_magazine'] == 1) {
                    //如果当前用户为已购买年份杂志状态
                    //半年
                    if ($order['buy_type'] == 1) {
                        //修改用户信息
                        $update_user = [
                            'is_year_magazine' => 1,
                            'year_magazine_end_time' => $user['year_magazine_end_time'] - time() + strtotime("+6months", time()),  //半年时间
                        ];

                        //修改订单
                        $update_order = [
                            'status' => 1,                          //订单已完成
                            'pay_price' => $pay_price,      //支付金额
                            'pay_time' => time(),                   //支付时间
                            'is_pay' => 1,                          //已支付
                            'end_time' => $user['year_magazine_end_time'] - time() + strtotime("+6months", time()),  //半年时间
                        ];
                    }
                    //一年
                    if ($order['buy_type'] == 2) {
                        //修改用户信息
                        $update_user = [
                            'is_year_magazine' => 1,
                            'year_magazine_end_time' => $user['year_magazine_end_time'] - time() + strtotime("+1years", time()),  //一年时间
                        ];
                        //修改订单
                        $update_order = [
                            'status' => 1,                         //订单已完成
                            'pay_price' => $pay_price,             //支付金额
                            'pay_time' => time(),                  //支付时间
                            'is_pay' => 1,                         //已支付
                            'end_time' => $user['year_magazine_end_time'] - time() + strtotime("+1years", time()),//一年时间
                        ];
                    }
                    //延长用户年份杂志 到期时间
                    $res1 = User::where('id', $order['user_id'])->update($update_user);

                    //修改订单中的开始与结束时间
                    $res = Order::where('sn', $data['out_trade_no'])->update($update_order);

                } else {
                    //如果之前的年份杂志已过期或之前没购买过年份杂志
                    //半年
                    if ($order['buy_type'] == 1) {
                        //修改用户信息
                        $update_user = [
                            'is_year_magazine' => 1,                                        //已购买年份杂志
                            'year_magazine_start_time' => time(),                           //当前时间
                            'year_magazine_end_time' => strtotime("+6months", time()),  //半年时间
                        ];
                        //修改订单
                        $update_order = [
                            'status' => 1,                         //订单已完成
                            'pay_price' => $pay_price,     //支付金额
                            'pay_time' => time(),                 //支付时间
                            'is_pay' => 1,                        // 已支付
                            'start_time' => time(),
                            'end_time' => strtotime("+6months", time()),
                        ];
                    }
                    //一年
                    if ($order['buy_type'] == 2) {
                        //修改用户信息
                        $update_user = [
                            'is_year_magazine' => 1,
                            'year_magazine_start_time' => time(),
                            'year_magazine_end_time' => strtotime("+1years", time()),  //一年时间
                        ];
                        //修改订单
                        $update_order = [
                            'status' => 1,                         //订单已完成
                            'pay_price' => $pay_price,             //支付金额
                            'pay_time' => time(),                  //支付时间
                            'is_pay' => 1,                         //已支付
                            'start_time' => time(),
                            'end_time' => strtotime("+1years", time()),
                        ];
                    }
                    //修改用户信息
                    $res1 = User::where('id', $order['user_id'])->update($update_user);

                    //修改订单
                    $res = Order::where('sn', $data['out_trade_no'])->update($update_order);

                }
                if ($res && $res1) {
                    return true;
                } else {
                    return false;
                }
            }


            //修改杂志类型订单
            if ($data['attach'] == 2) {
                //修改订单
                $update_order = [
                    'status' => 1,                             //订单已完成
                    'pay_price' => $pay_price,                 //支付金额
                    'pay_time' => time(),                      //支付时间
                    'is_pay' => 1,                             //已支付
                ];
                //修改订单
                $res = Order::where('sn', $data['out_trade_no'])->update($update_order);

                //新增订阅数据
                $create_magazine_subscribe = [
                    'is_forever' => 1,                         //永久有效
                    'status' => 1,                         //有效
                    'type' => 2,                         //杂志
                    'user_id' => $order['user_id'],         //用户ID
                    'pid' => $order['pid'],             //产品ID
                    'create_time' => time(),                   //订阅时间
                ];

                //判断订阅表中有没有此条数据如果有就不在添加
                $is_sub = UserSubscribe::field('id')->where('pid', $order['pid'])->where('user_id', $order['user_id'])->where('type', 2)->find();
                //新增订阅
                $obj = new UserSubscribe();
                if (empty($is_sub)) {
                    $obj->data($create_magazine_subscribe);
                    $res1 = $obj->isUpdate(false)->save();
                    //subscribe_count 修改订阅数量 +1
                    User::where('id', $order['user_id'])->setInc('subscribe_count');
                    //修改杂志购买人数 +1
                    Magazine::where('id', $order['pid'])->setInc('buy_count');
                    //修改杂志订阅人数 +1
                    Magazine::where('id', $order['pid'])->setInc('subscribe_count');

                } else {
                    $res1 = $obj->where('id', $is_sub['id'])->update($create_magazine_subscribe);
                }

                if ($res && $res1) {
                    return true;
                } else {
                    return false;
                }


            }


            //修改小课类型订单
            if ($data['attach'] == 3) {
                //修改订单
                $update_order = [
                    'status' => 1,                         //订单已完成
                    'pay_price' => $pay_price,             //支付金额
                    'pay_time' => time(),                  //支付时间
                    'is_pay' => 1,                         //已支付
                ];
                //修改订单
                $res = Order::where('sn', $data['out_trade_no'])->update($update_order);
                //新增小课购买数据
                $create_course_subscribe = [
                    'is_forever' => 1,                     //永久有效
                    'status' => 1,                     //有效
                    'type' => 3,                     //小课
                    'user_id' => $order['user_id'],     //用户ID
                    'pid' => $order['pid'],         //产品ID
                    'create_time' => time(),               //订阅时间
                ];
                //查询订阅表中是否已有该条订阅
                $is_sub = UserSubscribe::field('id')->where('pid', $order['pid'])->where('user_id', $order['user_id'])->where('type', 3)->find();

                $obj = new UserSubscribe();

                if (empty($is_sub)) {
                    $obj->data($create_course_subscribe);
                    $res1 = $obj->save();
                    //subscribe_count 修改订阅数量 +1
                    User::where('id', $order['user_id'])->setInc('subscribe_count');
                    //修改小课购买人数 +1
                    Course::where('id', $order['pid'])->setInc('buy_count');
                    //修改小课订阅人数 +1
                    Course::where('id', $order['pid'])->setInc('subscribe_count');
                } else {
                    $res1 = $obj->where('id', $is_sub['id'])->update($create_course_subscribe);
                }

                if ($res && $res1) {
                    return true;
                } else {
                    return false;
                }
            }


            //修改TK 类型订单
            if ($data['attach'] == 4) {
                $update_order = [
                    'status' => 1,                         //订单已完成
                    'pay_price' => $pay_price,             //支付金额
                    'pay_time' => time(),                  //支付时间
                    'is_pay' => 1,                         // 已支付
                ];
                //修改订单
                $res = Order::where('sn', $data['out_trade_no'])->update($update_order);
                //新增TKshow 购买数量
                $create_talkshow_subscribe = [
                    'is_forever' => 1,                     //永久有效
                    'status' => 1,                     //有效
                    'type' => 4,                     //小课
                    'user_id' => $order['user_id'],     //用户ID
                    'pid' => $order['pid'],         //产品ID
                    'create_time' => time(),               //订阅时间
                ];
                //判断用户是否有订阅过此TKS
                $is_sub = UserSubscribe::field('id')->where('pid', $order['pid'])->where('user_id', $order['user_id'])->where('type', 4)->find();

                //新增
                $obj = new UserSubscribe();
                if (empty($is_sub)) {
                    $obj->data($create_talkshow_subscribe);
                    $res1 = $obj->save();
                    //subscribe_count 修改订阅数量 +1
                    User::where('id', $order['user_id'])->setInc('subscribe_count');
                    //修改TalkShow购买人数 +1
                    TalkShow::where('id', $order['pid'])->setInc('buy_count');
                    //修改TalkShow订阅人数 +1
                    TalkShow::where('id', $order['pid'])->setInc('subscribe_count');
                } else {
                    $res1 = $obj->where('id', $is_sub['id'])->update($create_talkshow_subscribe);
                }
                if ($res && $res1) {
                    return true;
                } else {
                    return false;
                }

            }

            if ($data['attach'] == 5) {
                //如果用户是VIP  ,续费
                if ($user['is_vip'] == 1) {
                    //设置VIP订单的开始结束时间
                    $update_order = [
                        'status' => 1,                         //订单已完成
                        'pay_price' => $pay_price,             //支付金额
                        'pay_time' => time(),                  //支付时间
                        'is_pay' => 1,                         //已支付
                        'start_time' => time(),
                        'end_time' => $user['vip_end_time'] - time() + strtotime("+1years", time()),   //上一次购买VIP的结束时间
                    ];
                    $res = Order::where('sn', $data['out_trade_no'])->update($update_order);
                    //设置用户VIP结束时间时间
                    $update_vip_time = $user['vip_end_time'] - time() + strtotime("+1years", time());
                    //修改用户VIP结束时间
                    $res1 = User::where('id', $order['user_id'])->setField('vip_end_time', $update_vip_time);
                } else {
                    //如果用户不是VIP,直接修改时间
                    $update_user_vip = [
                        'vip_start_time' => time(),
                        'vip_end_time' => strtotime("+1years", time()),
                        'is_vip' => 1
                    ];
                    $order_update = [
                        'status' => 1,                                         //订单已完成
                        'pay_price' => $pay_price,                             //支付金额
                        'pay_time' => time(),                                  //支付时间
                        'is_pay' => 1,                                         //已支付
                        'start_time' => time(),                                //VIP开始时间
                        'end_time' => strtotime("+1years", time()),       //VIP结束时间
                    ];
                    //修改VIP订单 开始结束时间
                    $res = Order::where('sn', $data['out_trade_no'])->update($order_update);
                    //修改用户VIP信息
                    $res1 = User::where('id', $order['user_id'])->update($update_user_vip);

                }
                if ($res && $res1) {
                    return true;
                } else {
                    return false;
                }

            }


        }
    }





    /**
     * 获取微信支付订单参数
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function pay_data()
    {
        $order_id=input('order_id','');
        if (empty($order_id)){
            json_fail([
                'status'=>-1,
                'msg'=>'缺少订单ID'
            ]);
        }
        //查询订单信息 订单号  订单类型  杂志年份类型 购买费用
        $order=Order::where('id',$order_id)->field('id,sn,type,buy_type,price')->find();
        if (!$order){
            json_fail([
                'status' => -2,
                'msg' => '订单信息不存在！'
            ]);
        }
        //查询用户信息  openID
        $user=User::where('id',UID)->field('id,openid')->find();
        if (empty($user)) {
           json_fail('用户信息不存在!');
        }

        $data['openid']=$user['openid'];    //用户OPENID
        $data['body']='环球人物-杂志订阅';
        $data['attach']=$order['type'];     //自定义参数 ,选择传入订单类型
        $data['sn']=$order['sn'];           //订单号
        $data['total_fee']=$order['price']; //订单金额

        $jsApiParameters = $this->order_pay($data);

        echo $jsApiParameters;
    }


    /**
     * 微信支付
     * @throws \WxPayException
     * @throws \think\Exception
     * @author jihaichuan
     */
    public function order_pay($data){
        if (empty($data)){
            return '参数错误';
        }
        // 回调地址
        $notify_url = \think\Config::get('server_url').'/Api/Pay/order_notify_url';
        //调用
        vendor('Wxpay.WxPay#Api');
        vendor('Wxpay.WxPayUnifiedOrder');
        vendor('Wxpay.WxPayResults');
        vendor('Wxpay.JsApiPay');
        //WxPayUnifiedOrder

        $input = new \WxPayUnifiedOrder();
        $input->SetBody($data['body']);
        $input->SetAttach($data['attach']);
        //$input->SetDetail($goodsDataStr);
        $input->SetOut_trade_no($data['sn']);   //WxPayConfig::MCHID.date("YmdHis")$user_activity_data['price']
        $input->SetTotal_fee($data['total_fee']);//$order_data['pay_price']
//        $input->SetTotal_fee('5');
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag("test");
        $input->SetNotify_url($notify_url);
        $input->SetTrade_type('JSAPI');
        $input->SetOpenid($data['openid']);

        $order = \WxPayApi::unifiedOrder($input);
        $tools = new \JsApiPay();
        // 创建调用信息
        $jsApiParameters = $tools->GetJsApiParameters($order);
        return $jsApiParameters;
    }




    /**
     * 退款开发调试接口
     * Date: 2019/2/27
     * Time: 17:36
     * USER:GCQ
     */
    public function  order_refund()
    {
        $total_price=input('post.total_price','');
        $return_price=input('post.return_price',0);   //退款金额
        $sn=input('post.sn','');
        if (empty($sn)){
            json_fail('退款订单不存在');
        }
        if (empty($total_price)) {
              json_fail('缺少支付金额');
        }
        if (empty($return_price)) {
            json_fail('缺少退款金额');
        }

                //退款数据
                $wx_refund_data=[
                    'sn'=>$sn,                                       //原支付订单编号
                    'total_price'=>$total_price,                 //订单支付金额
                    'return_price'=>$return_price,                            //退款金额   后写输入的金额
                ];

                //调用退款方法
                $refund_status= $this->wxRefund($wx_refund_data);

                //判断退款状态 成功 后修改相关数据
                if ($refund_status['return_code']=='SUCCESS' && $refund_status['result_code']=='SUCCESS'){
                    json_success('退款成功');
                }
                json_success($refund_status);
    }

    /**
     * 微信退款
     */
    function wxRefund($data)
    {
        vendor('Wxpay.WxPay#Api');
        vendor('Wxpay.WxPayRefund');
        vendor('Wxpay.WxPayResults');
        //实例化数据库
        $merchid = \WxPayConfig::MCHID;
        $input = new \WxPayRefund();

        $input->SetOut_trade_no($data['sn']);         //自己的订单号
//            $input->SetTransaction_id($infoList['transaction_id']);     //微信官方生成的订单流水号，在支付成功中有返回   与out_trade_no  二选一
        $input->SetOut_refund_no(orderNum());                            //退款单号
        $input->SetTotal_fee($data['total_price']);                           //订单标价金额，单位为分
        $input->SetRefund_fee($data['return_price']);                    //$orderInfo['total_price']   //$userDeposit['deposit_price']   //退款总金额，订单总金额，单位为分，只能为整数
        $input->SetOp_user_id($merchid);

        $result = \WxPayApi::refund($input);                                   //退款
        return $result;
    }






    /**
     * 支付成功后写入回调表
     */
    public function addCallback($xmlArr)
    {
        // 支付成功后，写入回调表
        $wxcalback = new \app\api\model\WxCallback();
        $info = $wxcalback->where(array('out_trade_no' => $xmlArr['out_trade_no']))->find();
        if (!$info) {
            $data = array(
                'return_code' => $xmlArr['return_code'],
                'return_msg' => '',
                'appid' => $xmlArr['appid'],
                'mch_id' => $xmlArr['mch_id'],
                'device_info' => '',
                'nonce_str' => $xmlArr['nonce_str'],
                'sign' => $xmlArr['sign'],
                'result_code' => $xmlArr['result_code'],
                'err_code' => '',
                'err_code_des' => '',
                'openid' => $xmlArr['openid'],
                'is_subscribe' => $xmlArr['is_subscribe'],
                'trade_type' => $xmlArr['trade_type'],
                'bank_type' => $xmlArr['bank_type'],
                'total_fee' => $xmlArr['total_fee'],
                'fee_type' => $xmlArr['fee_type'],
                'cash_fee' => $xmlArr['cash_fee'],
                'cash_fee_type' => '',
                'coupon_fee' => '',
                'coupon_count' => '',
                'transaction_id' => $xmlArr['transaction_id'],
                'out_trade_no' => $xmlArr['out_trade_no'],
                'attach' => $xmlArr['attach'],
                'time_end' => $xmlArr['time_end']
            );
            $wxcalback->create($data, true);
        }
    }

}